document.addEventListener('DOMContentLoaded', function () {
  try {
    // 检查管理员登录状态
    checkAdminLogin();

    // 初始化标签页切换
    initTabs();

    // 初始化用户筛选
    initFilters();

    // 初始化模态框
    initModal();

    // 初始化搜索功能
    initSearch();

    // 初始化刷新按钮
    initRefreshButtons();

    // 绑定登出按钮
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
      logoutBtn.addEventListener('click', adminLogout);
    }

    // 添加教师页面链接
    addTeacherPageNavLink();

    // 获取待审核的信息修改申请
    fetchPendingInfoModifications();

    // 身份模块tab点击事件
    const identityTabBtn = document.querySelector('.admin-tab[data-tab="identity"]');
    const identityTabContent = document.getElementById('identityTab');
    const infoEditTabContent = document.getElementById('infoEditTab');

    if (identityTabBtn && identityTabContent && infoEditTabContent) {
      identityTabBtn.addEventListener('click', function () {
        identityTabContent.style.display = 'block';
        infoEditTabContent.style.display = 'none';
      });
    }

    // 课程数据数组
    var courseList = [];
    // 课程筛选后的数组
    var filteredCourseList = [];

    // 获取并渲染课程表
    fetchAndRenderCourses();

    // 绑定新增课程表单事件
    bindAddCourseForm();

    // 动态填充教师下拉框
    fillTeacherSelect();

    // 绑定课程查询按钮事件
    bindCourseSearch();

    // 绑定全选checkbox
    var selectAll = document.getElementById('selectAllCourses');
    var checkboxes = document.querySelectorAll('.course-checkbox');
    if (selectAll) {
      selectAll.checked = false;
      selectAll.onclick = function () {
        checkboxes.forEach(cb => { cb.checked = selectAll.checked; });
      };
    }

    // 绑定批量删除按钮事件
    bindBatchDeleteCourses();

    // 绑定编辑课程表单事件
    bindEditCourseForm();
  } catch (error) {
    console.error('初始化页面时出错:', error);
  }
});

// 检查管理员登录状态
function checkAdminLogin() {
  const adminToken = localStorage.getItem('adminToken');

  if (!adminToken) {
    // 未登录，跳转回登录页
    window.location.href = 'index.html';
    return;
  }

  // 简单验证令牌格式
  if (adminToken.split('.').length !== 3) {
    console.error('管理员令牌格式无效');
    adminLogout();
    return;
  }

  // 加载用户数据
  loadUsers();
}

// 加载用户数据
async function loadUsers() {
  try {
    console.log('开始加载用户数据');
    console.log('使用的管理员令牌:', localStorage.getItem('adminToken'));

    // 创建一个通用的获取用户列表函数
    async function fetchUsers(status) {
      console.log(`尝试获取${status}状态的用户`);
      const response = await fetch(`/api/admin/users?status=${status}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
        }
      });

      console.log(`${status}用户请求状态码:`, response.status);

      if (!response.ok) {
        if (response.status === 401) {
          console.error('认证失败，管理员令牌无效');
          adminLogout();
          return null;
        }
        throw new Error(`获取${status}用户失败`);
      }

      const data = await response.json();
      console.log(`获取到${status}用户数据:`, data);
      return data;
    }

    // 获取各种状态的用户
    const pendingData = await fetchUsers('pending');
    if (pendingData) {
      renderUserTable('pendingUserTable', pendingData.users || []);
    }

    const approvedData = await fetchUsers('approved');
    if (approvedData) {
      renderUserTable('approvedUserTable', approvedData.users || []);
    }

    const rejectedData = await fetchUsers('rejected');
    if (rejectedData) {
      renderUserTable('rejectedUserTable', rejectedData.users || []);
    }

    return true; // 确保函数返回一个Promise
  } catch (error) {
    console.error('Error loading users:', error);
    alert('加载用户数据失败，请重试');
    return false;
  }
}

// 渲染用户表格
function renderUserTable(tableId, users) {
  const table = document.getElementById(tableId);
  const tbody = table.querySelector('tbody');
  tbody.innerHTML = '';

  if (users.length === 0) {
    const tr = document.createElement('tr');
    tr.innerHTML = `<td colspan="${tableId === 'rejectedUserTable' ? 7 : 6}" style="text-align: center;">暂无数据</td>`;
    tbody.appendChild(tr);
    return;
  }

  users.forEach(user => {
    const tr = document.createElement('tr');
    tr.dataset.userId = user.id;
    tr.dataset.role = user.role;

    if (tableId === 'pendingUserTable') {
      tr.innerHTML = `
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${translateRole(user.role)}</td>
                <td>${formatDate(user.created_at)}</td>
                <td>
                    <button class="action-btn details-btn" data-user-id="${user.id}">查看详情</button>
                    <button class="action-btn delete-btn" data-user-id="${user.id}">删除</button>
                </td>
            `;
    } else if (tableId === 'approvedUserTable') {
      tr.innerHTML = `
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${translateRole(user.role)}</td>
                <td>${formatDate(user.approval_date)}</td>
                <td>
                    <button class="action-btn details-btn" data-user-id="${user.id}">查看详情</button>
                    <button class="action-btn delete-btn" data-user-id="${user.id}">删除</button>
                </td>
            `;
    } else if (tableId === 'rejectedUserTable') {
      tr.innerHTML = `
                <td>${user.id}</td>
                <td>${user.username}</td>
                <td>${user.email}</td>
                <td>${translateRole(user.role)}</td>
                <td>${formatDate(user.rejection_date)}</td>
                <td>${user.rejection_reason || '无'}</td>
                <td>
                    <button class="action-btn details-btn" data-user-id="${user.id}">查看详情</button>
                    <button class="action-btn approve-btn" data-user-id="${user.id}">批准</button>
                    <button class="action-btn delete-btn" data-user-id="${user.id}">删除</button>
                </td>
            `;
    }

    tbody.appendChild(tr);
  });

  // 绑定详情按钮事件
  const detailBtns = tbody.querySelectorAll('.details-btn');
  detailBtns.forEach(btn => {
    btn.addEventListener('click', function () {
      const userId = this.dataset.userId;
      showUserDetails(userId);
    });
  });

  // 绑定拒绝用户的批准按钮
  if (tableId === 'rejectedUserTable') {
    const approveBtns = tbody.querySelectorAll('.approve-btn');
    approveBtns.forEach(btn => {
      btn.addEventListener('click', function () {
        const userId = this.dataset.userId;
        approveUser(userId);
      });
    });
  }

  // 绑定删除按钮事件
  const deleteBtns = tbody.querySelectorAll('.delete-btn');
  deleteBtns.forEach(btn => {
    btn.addEventListener('click', function () {
      const userId = this.dataset.userId;
      deleteUser(userId);
    });
  });
}

// 初始化标签页切换
function initTabs() {
  const tabMap = {
    student: 'info-editTab',
    teacher: 'courseModuleContent',
    identity: 'identityTab'
  };
  const titleTextMap = {
    student: '信息修改模块',
    teacher: '课程模块',
    identity: '审核模块'
  };
  const tabs = document.querySelectorAll('.admin-tab');
  const tabContents = document.querySelectorAll('.admin-tab-content');
  const titleSpan = document.getElementById('mainModuleTitleText');

  tabs.forEach(tab => {
    tab.addEventListener('click', function () {
      // 移除所有tab的active
      tabs.forEach(t => t.classList.remove('active'));
      this.classList.add('active');
      // 隐藏所有内容区
      tabContents.forEach(c => c.style.display = 'none');
      // 显示对应内容区
      const tabName = this.dataset.tab;
      const contentId = tabMap[tabName];
      if (contentId) {
        const contentDiv = document.getElementById(contentId);
        if (contentDiv) contentDiv.style.display = 'block';
      }
      // 切换标题
      if (titleSpan && titleTextMap[tabName]) {
        titleSpan.textContent = titleTextMap[tabName];
      }
    });
  });

  // 页面初始化时只显示身份模块内容
  tabContents.forEach(c => c.style.display = 'none');
  const identityContent = document.getElementById('identityTab');
  if (identityContent) identityContent.style.display = 'block';
  if (titleSpan) titleSpan.textContent = titleTextMap['identity'];
}

// 初始化筛选按钮
function initFilters() {
  try {
    const filterGroups = document.querySelectorAll('.user-status-filter');
    if (!filterGroups || filterGroups.length === 0) {
      console.warn('未找到筛选按钮组');
      return;
    }

    filterGroups.forEach(group => {
      if (!group) return;

      const buttons = group.querySelectorAll('.filter-btn');
      if (!buttons || buttons.length === 0) {
        console.warn('未找到筛选按钮');
        return;
      }

      const tableContainer = group.closest('.admin-tab-content');
      if (!tableContainer) {
        console.warn('未找到表格容器');
        return;
      }

      const tableElement = tableContainer.querySelector('.user-list');
      if (!tableElement) {
        console.warn('未找到用户列表表格');
        return;
      }

      const tableId = tableElement.id;

      buttons.forEach(btn => {
        if (!btn) return;

        btn.addEventListener('click', function () {
          // 移除所有活动状态
          buttons.forEach(b => {
            if (b) b.classList.remove('active');
          });

          // 设置当前按钮为活动状态
          this.classList.add('active');

          // 过滤表格
          const role = this.dataset.role;
          if (tableId) {
            filterTable(tableId, role);
          }
        });
      });
    });
  } catch (error) {
    console.error('初始化筛选按钮时出错:', error);
  }
}

// 根据角色过滤表格
function filterTable(tableId, role) {
  try {
    const table = document.getElementById(tableId);
    if (!table) {
      console.warn(`未找到表格: ${tableId}`);
      return;
    }

    const rows = table.querySelectorAll('tbody tr');
    if (!rows || rows.length === 0) {
      console.warn(`表格 ${tableId} 中没有行数据`);
      return;
    }

    rows.forEach(row => {
      if (!row) return;

      if (role === 'all' || row.dataset.role === role) {
        row.style.display = '';
      } else {
        row.style.display = 'none';
      }
    });
  } catch (error) {
    console.error(`过滤表格 ${tableId} 时出错:`, error);
  }
}

// 初始化模态框
function initModal() {
  const modal = document.getElementById('userDetailModal');
  const closeBtn = modal.querySelector('.close-modal');

  // 关闭模态框
  closeBtn.addEventListener('click', function () {
    modal.style.display = 'none';
  });

  // 点击模态框外部关闭
  window.addEventListener('click', function (event) {
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });

  // 绑定审核按钮
  const approveUserBtn = document.getElementById('approveUserBtn');
  const rejectUserBtn = document.getElementById('rejectUserBtn');

  if (approveUserBtn) {
    approveUserBtn.addEventListener('click', function () {
      const userId = this.dataset.userId;
      const comment = document.getElementById('approvalComment').value;
      console.log('批准用户:', userId, '评论:', comment);
      approveUser(userId, comment);
    });
  }

  if (rejectUserBtn) {
    rejectUserBtn.addEventListener('click', function () {
      const userId = this.dataset.userId;
      const comment = document.getElementById('approvalComment').value;

      if (!comment.trim()) {
        alert('请输入拒绝原因');
        return;
      }

      console.log('拒绝用户:', userId, '原因:', comment);
      rejectUser(userId, comment);
    });
  }

  // 新增课程模态框弹出与关闭
  var addBtn = document.getElementById('addBtn');
  var addCourseModal = document.getElementById('addCourseModal');
  var closeAddCourseModal = document.getElementById('closeAddCourseModal');
  var cancelAddCourseBtn = document.getElementById('cancelAddCourseBtn');
  if (addBtn && addCourseModal) {
    addBtn.addEventListener('click', function () {
      addCourseModal.style.display = 'block';
    });
  }
  if (closeAddCourseModal && addCourseModal) {
    closeAddCourseModal.addEventListener('click', function () {
      addCourseModal.style.display = 'none';
    });
  }
  if (cancelAddCourseBtn && addCourseModal) {
    cancelAddCourseBtn.addEventListener('click', function () {
      addCourseModal.style.display = 'none';
    });
  }
  window.addEventListener('click', function (event) {
    if (event.target === addCourseModal) {
      addCourseModal.style.display = 'none';
    }
  });
}

// 显示用户详情
async function showUserDetails(userId) {
  try {
    console.log('请求用户详情，ID:', userId);

    const response = await fetch(`/api/admin/user/${userId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      }
    });

    if (!response.ok) {
      throw new Error('Failed to load user details');
    }

    const data = await response.json();
    console.log('获取到用户详情数据:', data);

    if (!data.success || !data.user) {
      throw new Error('获取用户数据失败');
    }

    const user = data.user;

    // 填充详情列表
    const detailList = document.getElementById('userDetailList');
    detailList.innerHTML = '';

    // 基本信息
    const basicInfo = [
      { label: '用户ID', value: user.id || '无' },
      { label: '用户名', value: user.username || '无' },
      { label: '电子邮箱', value: user.email || '无' },
      { label: '身份', value: translateRole(user.role) || '无' },
      { label: '注册时间', value: formatDate(user.created_at) || '无' },
      { label: '状态', value: translateStatus(user.status) || '无' }
    ];

    basicInfo.forEach(item => {
      const li = document.createElement('li');
      li.innerHTML = `<span class="detail-label">${item.label}:</span> ${item.value}`;
      detailList.appendChild(li);
    });

    // 用户详细信息
    if (user.profile) {
      const profile = [
        { label: '真实姓名', value: user.profile.real_name || '无' },
        { label: '联系电话', value: user.profile.contact_number || '无' }
      ];

      if (user.role === 'student') {
        profile.push(
          { label: '学号', value: user.profile.student_id || '无' },
          { label: '院系', value: user.profile.department || '无' },
          { label: '班级', value: user.profile.class_name || '无' }
        );
      } else if (user.role === 'teacher') {
        profile.push(
          { label: '所属院系', value: user.profile.department || '无' }
        );
      }

      profile.forEach(item => {
        const li = document.createElement('li');
        li.innerHTML = `<span class="detail-label">${item.label}:</span> ${item.value}`;
        detailList.appendChild(li);
      });
    }

    // 设置审核操作的用户ID
    const approveBtn = document.getElementById('approveUserBtn');
    const rejectBtn = document.getElementById('rejectUserBtn');

    if (approveBtn) approveBtn.dataset.userId = userId;
    if (rejectBtn) rejectBtn.dataset.userId = userId;

    console.log('设置按钮ID:', userId,
      '批准按钮:', approveBtn ? '已找到' : '未找到',
      '拒绝按钮:', rejectBtn ? '已找到' : '未找到');

    // 根据用户状态显示/隐藏审核操作区域
    const approvalActions = document.getElementById('approvalActions');

    if (approvalActions) {
      if (user.status === 'pending' || user.status === 'rejected') {
        approvalActions.style.display = 'block';
      } else {
        approvalActions.style.display = 'none';
      }
    }

    // 显示模态框
    const modal = document.getElementById('userDetailModal');
    if (modal) {
      modal.style.display = 'block';
    } else {
      console.error('找不到模态框元素');
    }

  } catch (error) {
    console.error('Error loading user details:', error);
    alert('加载用户详情失败，请重试');
  }
}

// 批准用户
async function approveUser(userId, comment = '') {
  if (!userId) {
    console.error('错误：找不到用户ID');
    alert('操作失败：未能获取用户信息');
    return;
  }

  try {
    console.log('调用批准API，用户ID:', userId);
    const response = await fetch(`/api/admin/approve/${userId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      },
      body: JSON.stringify({ comment })
    });

    if (!response.ok) {
      throw new Error('Failed to approve user');
    }

    const data = await response.json();

    if (data.success) {
      alert('用户已成功批准');
      // 关闭模态框
      const modal = document.getElementById('userDetailModal');
      if (modal) {
        modal.style.display = 'none';
      }

      // 获取当前激活的标签页
      const activeTab = document.querySelector('.identity-tab.active');
      if (activeTab) {
        const tabName = activeTab.dataset.identityTab;
        console.log('当前激活的标签页:', tabName);

        // 如果当前是已拒绝用户页签，重新加载该页签
        if (tabName === 'rejected') {
          const refreshBtn = document.getElementById('refreshRejectedBtn');
          if (refreshBtn) {
            refreshBtn.click();
          }
        }

        // 同时刷新已批准用户页签
        const approvedRefreshBtn = document.getElementById('refreshApprovedBtn');
        if (approvedRefreshBtn) {
          approvedRefreshBtn.click();
        }
      } else {
        // 重新加载所有用户数据
        loadUsers();
      }
    } else {
      alert(data.message || '批准用户失败');
    }

  } catch (error) {
    console.error('Error approving user:', error);
    alert('批准用户失败，请重试');
  }
}

// 拒绝用户
async function rejectUser(userId, comment) {
  if (!userId) {
    console.error('错误：找不到用户ID');
    alert('操作失败：未能获取用户信息');
    return;
  }

  if (!comment || comment.trim() === '') {
    alert('请输入拒绝原因');
    return;
  }

  try {
    console.log('调用拒绝API，用户ID:', userId, '原因:', comment);
    const response = await fetch(`/api/admin/reject/${userId}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      },
      body: JSON.stringify({ comment })
    });

    if (!response.ok) {
      throw new Error('Failed to reject user');
    }

    const data = await response.json();

    if (data.success) {
      alert('已拒绝该用户');
      // 关闭模态框
      const modal = document.getElementById('userDetailModal');
      if (modal) {
        modal.style.display = 'none';
      }

      // 获取当前激活的标签页
      const activeTab = document.querySelector('.identity-tab.active');
      if (activeTab) {
        const tabName = activeTab.dataset.identityTab;
        console.log('当前激活的标签页:', tabName);

        // 如果当前是待审核或已批准用户页签，重新加载该页签
        if (tabName === 'pending' || tabName === 'approved') {
          const refreshBtn = document.getElementById(`refresh${tabName.charAt(0).toUpperCase() + tabName.slice(1)}Btn`);
          if (refreshBtn) {
            refreshBtn.click();
          }
        }

        // 同时刷新已拒绝用户页签
        const rejectedRefreshBtn = document.getElementById('refreshRejectedBtn');
        if (rejectedRefreshBtn) {
          rejectedRefreshBtn.click();
        }
      } else {
        // 重新加载所有用户数据
        loadUsers();
      }
    } else {
      alert(data.message || '拒绝用户失败');
    }

  } catch (error) {
    console.error('Error rejecting user:', error);
    alert('拒绝用户失败，请重试');
  }
}

// 管理员登出
function adminLogout() {
  localStorage.removeItem('adminToken');
  window.location.href = 'index.html';
}

// 辅助函数

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return '无';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
}

// 角色翻译
function translateRole(role) {
  const roles = {
    'student': '学生',
    'teacher': '教师',
    'admin': '管理员'
  };

  return roles[role] || role;
}

// 状态翻译
function translateStatus(status) {
  const statuses = {
    'pending': '待审核',
    'approved': '已批准',
    'rejected': '已拒绝'
  };

  return statuses[status] || status;
}

// 删除用户
async function deleteUser(userId) {
  try {
    console.log('尝试删除用户:', userId);

    if (!confirm(`确定要删除ID为 ${userId} 的用户吗？此操作不可撤销。`)) {
      return;
    }

    const response = await fetch(`/api/admin/user/${userId}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      }
    });

    if (!response.ok) {
      throw new Error('Failed to delete user');
    }

    const data = await response.json();

    if (data.success) {
      alert('用户已成功删除');

      // 获取当前激活的标签页
      const activeTab = document.querySelector('.identity-tab.active');
      if (activeTab) {
        const tabName = activeTab.dataset.identityTab;
        console.log('当前激活的标签页:', tabName);

        // 触发对应标签页的刷新按钮，重新加载用户数据
        const refreshBtn = document.getElementById(`refresh${tabName.charAt(0).toUpperCase() + tabName.slice(1)}Btn`);
        if (refreshBtn) {
          refreshBtn.click();
        } else {
          // 如果找不到特定的刷新按钮，则重新加载所有用户数据
          loadUsers();
        }
      } else {
        // 重新加载所有用户数据
        loadUsers();
      }
    } else {
      alert(data.message || '删除用户失败');
    }

  } catch (error) {
    console.error('Error deleting user:', error);
    alert('删除用户失败，请重试');
  }
}

// 初始化搜索功能
function initSearch() {
  try {
    const searchInputs = {
      pending: document.getElementById('pendingSearchInput'),
      approved: document.getElementById('approvedSearchInput'),
      rejected: document.getElementById('rejectedSearchInput')
    };

    const searchButtons = {
      pending: document.getElementById('pendingSearchBtn'),
      approved: document.getElementById('approvedSearchBtn'),
      rejected: document.getElementById('rejectedSearchBtn')
    };

    // 为每个状态添加搜索事件
    for (const status in searchInputs) {
      const input = searchInputs[status];
      const button = searchButtons[status];

      if (input && button) {
        // 按钮点击搜索
        button.addEventListener('click', function () {
          const searchText = input.value.toLowerCase();
          searchTable(`${status}UserTable`, searchText);
        });

        // 输入框回车搜索
        input.addEventListener('keypress', function (e) {
          if (e.key === 'Enter') {
            const searchText = this.value.toLowerCase();
            searchTable(`${status}UserTable`, searchText);
          }
        });
      } else {
        console.warn(`未找到搜索元素: ${status}`, {
          input: input ? '存在' : '不存在',
          button: button ? '存在' : '不存在'
        });
      }
    }
  } catch (error) {
    console.error('初始化搜索功能时出错:', error);
  }
}

// 搜索表格内容
function searchTable(tableId, searchText) {
  try {
    const table = document.getElementById(tableId);
    if (!table) {
      console.warn(`未找到表格: ${tableId}`);
      return;
    }

    const rows = table.querySelectorAll('tbody tr');
    if (!rows || rows.length === 0) {
      console.log(`表格 ${tableId} 中没有行数据可搜索`);
      return;
    }

    let hasResults = false;

    rows.forEach(row => {
      if (!row || !row.cells || row.cells.length < 3) {
        return; // 跳过没有足够单元格的行
      }

      // 先重置任何之前的过滤
      row.style.display = '';

      // 如果搜索文本为空，则显示所有行
      if (!searchText || !searchText.trim()) {
        hasResults = true;
        return;
      }

      // 在用户名和邮箱中搜索
      try {
        const username = row.cells[1].textContent.toLowerCase();
        const email = row.cells[2].textContent.toLowerCase();

        if (username.includes(searchText) || email.includes(searchText)) {
          hasResults = true;
          // 高亮搜索匹配部分
          const highlight = (text, term) => {
            if (!text || !term) return text;
            try {
              const regex = new RegExp(`(${term})`, 'gi');
              return text.replace(regex, '<span style="background-color: yellow; font-weight: bold;">$1</span>');
            } catch (e) {
              console.warn('高亮文本出错:', e);
              return text;
            }
          };

          if (searchText) {
            row.cells[1].innerHTML = highlight(row.cells[1].textContent, searchText);
            row.cells[2].innerHTML = highlight(row.cells[2].textContent, searchText);
          }
        } else {
          row.style.display = 'none';
        }
      } catch (cellError) {
        console.warn('处理表格单元格时出错:', cellError);
      }
    });

    // 处理无结果情况
    const tbody = table.querySelector('tbody');
    if (!tbody) return;

    const emptyRow = tbody.querySelector('.empty-search-row');

    if (!hasResults) {
      if (!emptyRow) {
        try {
          const colSpan = (table.querySelector('thead tr')?.cells?.length) || 6;
          const tr = document.createElement('tr');
          tr.className = 'empty-search-row';
          tr.innerHTML = `<td colspan="${colSpan}" style="text-align: center; padding: 20px;">
            <div class="empty-state">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <circle cx="11" cy="11" r="8"></circle>
                <line x1="21" y1="21" x2="16.65" y2="16.65"></line>
              </svg>
              <h4>未找到匹配结果</h4>
              <p>尝试其他搜索条件或清空搜索框</p>
            </div>
          </td>`;
          tbody.appendChild(tr);
        } catch (createError) {
          console.warn('创建空结果行时出错:', createError);
        }
      }
    } else if (emptyRow) {
      emptyRow.remove();
    }
  } catch (error) {
    console.error(`搜索表格 ${tableId} 时出错:`, error);
  }
}

// 初始化刷新按钮
function initRefreshButtons() {
  try {
    const refreshButtons = {
      pending: document.getElementById('refreshPendingBtn'),
      approved: document.getElementById('refreshApprovedBtn'),
      rejected: document.getElementById('refreshRejectedBtn')
    };

    for (const status in refreshButtons) {
      const button = refreshButtons[status];
      if (button) {
        button.addEventListener('click', function () {
          try {
            this.disabled = true;
            this.innerHTML = `
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="loading-icon" style="animation: spin 1s linear infinite;">
                <path d="M23 4v6h-6"></path>
                <path d="M1 20v-6h6"></path>
                <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10"></path>
                <path d="M20.49 15a9 9 0 0 1-14.85 3.36L1 14"></path>
              </svg>
              刷新中...
            `;

            // 添加旋转动画样式
            if (!document.getElementById('spin-style')) {
              const style = document.createElement('style');
              style.id = 'spin-style';
              style.textContent = `
                @keyframes spin {
                  0% { transform: rotate(0deg); }
                  100% { transform: rotate(360deg); }
                }
              `;
              document.head.appendChild(style);
            }

            // 清空搜索框
            const searchInput = document.getElementById(`${status}SearchInput`);
            if (searchInput) {
              searchInput.value = '';
            }

            // 重新加载数据
            const refreshButton = this;
            loadUsers().then(() => {
              refreshButton.disabled = false;
              refreshButton.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M23 4v6h-6"></path>
                  <path d="M1 20v-6h6"></path>
                  <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10"></path>
                  <path d="M20.49 15a9 9 0 0 1-14.85 3.36L1 14"></path>
                </svg>
                刷新数据
              `;
            }).catch(error => {
              console.error('刷新数据时出错:', error);
              refreshButton.disabled = false;
              refreshButton.innerHTML = `
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M23 4v6h-6"></path>
                  <path d="M1 20v-6h6"></path>
                  <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10"></path>
                  <path d="M20.49 15a9 9 0 0 1-14.85 3.36L1 14"></path>
                </svg>
                刷新数据
              `;
            });
          } catch (buttonError) {
            console.error('刷新按钮点击处理出错:', buttonError);
            this.disabled = false;
          }
        });
      } else {
        console.warn(`未找到刷新按钮: ${status}`);
      }
    }
  } catch (error) {
    console.error('初始化刷新按钮时出错:', error);
  }
}

// 获取本地存储的用户数据
function getLocalUserData() {
  try {
    const userData = localStorage.getItem('userData');
    return userData ? JSON.parse(userData) : null;
  } catch (error) {
    console.error('解析用户数据错误:', error);
    return null;
  }
}

// 添加教师页面导航链接
function addTeacherPageNavLink() {
  // 检查用户是否是教师
  function checkIfTeacher() {
    const userData = getLocalUserData();
    return userData && userData.role === 'teacher';
  }

  // 如果用户是教师，添加导航链接
  if (checkIfTeacher()) {
    const navBar = document.querySelector('.admin-navbar ul');
    if (navBar) {
      const teacherNavItem = document.createElement('li');
      const teacherNavLink = document.createElement('a');
      teacherNavLink.href = '/teacher.html';
      teacherNavLink.textContent = '教师工作台';
      teacherNavItem.appendChild(teacherNavLink);
      navBar.appendChild(teacherNavItem);
    }
  }
}

// 获取待审核的信息修改申请
async function fetchPendingInfoModifications() {
  try {
    const response = await fetch('/api/info-modification/pending');
    if (response.ok) {
      const data = await response.json();
      updateInfoModificationTable(data);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

// 更新信息修改申请表格
function updateInfoModificationTable(data) {
  const tbody = document.querySelector('#infoEditTable tbody');
  tbody.innerHTML = '';

  data.forEach(request => {
    const row = document.createElement('tr');
    row.innerHTML = `
            <td>${request.student_id}</td>
            <td>${request.name}</td>
            <td>基本信息修改</td>
            <td>${new Date(request.created_at).toLocaleString()}</td>
            <td>${request.status}</td>
            <td>
                <button class="action-btn details-btn" data-request-id="${request.request_id}">查看详情</button>
                <button class="action-btn approve-btn" data-request-id="${request.request_id}">批准</button>
                <button class="action-btn reject-btn" data-request-id="${request.request_id}">拒绝</button>
            </td>
        `;
    tbody.appendChild(row);
  });
}

// 处理审核操作
async function handleInfoModificationReview(requestId, action, comment) {
  try {
    const response = await fetch('/api/info-modification/review', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        request_id: requestId,
        action: action,
        comment: comment
      })
    });

    if (response.ok) {
      alert('审核操作已提交');
      fetchPendingInfoModifications(); // 刷新列表
    } else {
      throw new Error('审核操作已提交');
    }
  } catch (error) {
    console.error('Error:', error);
    alert('审核操作失败，请稍后重试');
  }
}

// 绑定审核按钮事件
document.addEventListener('click', function (e) {
  if (e.target.matches('.approve-btn')) {
    const requestId = e.target.dataset.requestId;
    const comment = document.getElementById('infoEditComment').value;
    handleInfoModificationReview(requestId, 'approve', comment);
  } else if (e.target.matches('.reject-btn')) {
    const requestId = e.target.dataset.requestId;
    const comment = document.getElementById('infoEditComment').value;
    if (!comment) {
      alert('请填写拒绝原因');
      return;
    }
    handleInfoModificationReview(requestId, 'reject', comment);
  }
});

// 页面加载时获取待审核申请
document.addEventListener('DOMContentLoaded', fetchPendingInfoModifications);

// 课程数据数组
var courseList = [];
// 课程筛选后的数组
var filteredCourseList = [];

// 获取并渲染课程表
async function fetchAndRenderCourses() {
  try {
    const res = await fetch('/api/courses');
    const data = await res.json();
    if (data.success) {
      courseList = data.courses;
      filteredCourseList = courseList; // 默认显示全部
      renderCourseTable();
    } else {
      courseList = [];
      filteredCourseList = [];
      renderCourseTable();
    }
  } catch (e) {
    courseList = [];
    filteredCourseList = [];
    renderCourseTable();
  }
}

// 渲染课程表（使用filteredCourseList）
function renderCourseTable() {
  var tbody = document.querySelector('#courseTable tbody');
  tbody.innerHTML = '';
  if (!filteredCourseList || filteredCourseList.length === 0) {
    var tr = document.createElement('tr');
    tr.innerHTML = '<td colspan="11" style="text-align:center;">暂无数据</td>';
    tbody.appendChild(tr);
    return;
  }
  filteredCourseList.forEach(function (course, idx) {
    var tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input type="checkbox" class="course-checkbox" value="${course.id}"></td>
      <td>${filteredCourseList.length - idx}</td>
      <td>${course.course_name}</td>
      <td>${course.course_type}</td>
      <td>${course.teacher_real_name || course.teacher}</td>
      <td>${course.credit}</td>
      <td>${course.student_count}</td>
      <td>${course.classroom}</td>
      <td>${course.weekday}</td>
      <td>${course.section}</td>
      <td>
        <button class="action-btn details-btn" onclick="editCourse(${idx})">编辑</button>
        <button class="action-btn course-delete-btn" style="margin-left:8px;" onclick="deleteCourse(${idx})">删除</button>
      </td>
    `;
    tbody.appendChild(tr);
  });
  // 绑定全选checkbox
  var selectAll = document.getElementById('selectAllCourses');
  var checkboxes = tbody.querySelectorAll('.course-checkbox');
  if (selectAll) {
    selectAll.checked = false;
    selectAll.onclick = function () {
      checkboxes.forEach(cb => { cb.checked = selectAll.checked; });
    };
  }
}

// 查询按钮事件
function bindCourseSearch() {
  var searchBtn = document.getElementById('searchBtn');
  var input = document.getElementById('courseNameInput');
  if (searchBtn && input) {
    searchBtn.addEventListener('click', function () {
      var keyword = input.value.trim();
      if (!keyword) {
        filteredCourseList = courseList;
      } else {
        filteredCourseList = courseList.filter(function (course) {
          return course.course_name && course.course_name.indexOf(keyword) !== -1;
        });
      }
      renderCourseTable();
    });
  }
}

// 新增课程表单提交
async function handleAddCourse(e) {
  e.preventDefault();
  var form = e.target;
  var course = {
    course_name: form.course_name.value,
    course_type: form.course_type.value,
    teacher: form.teacher.value,
    credit: parseInt(form.credit.value, 10),
    student_count: parseInt(form.student_count.value, 10),
    classroom: form.classroom.value,
    weekday: form.weekday.value,
    section: form.section.value
  };
  // 提交到后端
  try {
    const res = await fetch('/api/courses', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(course)
    });
    const data = await res.json();
    if (data.success) {
      document.getElementById('addCourseModal').style.display = 'none';
      form.reset();
      await fetchAndRenderCourses();
    } else {
      alert(data.message || '新增课程失败');
    }
  } catch (e) {
    alert('网络错误，新增课程失败');
  }
}

// 删除课程
async function deleteCourse(idx) {
  const course = courseList[idx];
  if (!course || !course.id) {
    alert('找不到课程ID，无法删除');
    return;
  }
  if (confirm('确定要删除该课程吗？')) {
    try {
      const res = await fetch(`/api/courses/${course.id}`, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' }
      });
      const data = await res.json();
      if (data.success) {
        alert('课程已删除');
        await fetchAndRenderCourses();
      } else {
        alert(data.message || '删除课程失败');
      }
    } catch (e) {
      alert('网络错误，删除课程失败');
    }
  }
}

// 编辑课程（弹窗编辑）
function editCourse(idx) {
  var course = filteredCourseList[idx];
  if (!course) return;
  document.getElementById('editCourseId').value = course.id;
  document.getElementById('editCourseName').value = course.course_name || '';
  document.getElementById('editCourseType').value = course.course_type || '必修';
  document.getElementById('editCourseTeacher').value = course.teacher_real_name || course.teacher || '';
  document.getElementById('editCourseCredit').value = course.credit || '';
  document.getElementById('editCourseStudentCount').value = course.student_count || '';
  document.getElementById('editCourseClassroom').value = course.classroom || '';
  document.getElementById('editCourseWeekday').value = course.weekday || '周一';
  document.getElementById('editCourseSection').value = course.section || '第一大节';
  document.getElementById('editCourseModal').style.display = 'block';
}

// 绑定编辑课程表单事件
function bindEditCourseForm() {
  var form = document.getElementById('editCourseForm');
  if (!form) return;
  form.onsubmit = async function (e) {
    e.preventDefault();
    var id = document.getElementById('editCourseId').value;
    var course = {
      course_name: document.getElementById('editCourseName').value,
      course_type: document.getElementById('editCourseType').value,
      teacher: document.getElementById('editCourseTeacher').value,
      credit: parseInt(document.getElementById('editCourseCredit').value, 10),
      student_count: parseInt(document.getElementById('editCourseStudentCount').value, 10),
      classroom: document.getElementById('editCourseClassroom').value,
      weekday: document.getElementById('editCourseWeekday').value,
      section: document.getElementById('editCourseSection').value
    };
    console.log('编辑课程参数:', id, course);
    try {
      const res = await fetch(`/api/courses/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(course)
      });
      const data = await res.json();
      console.log('编辑课程响应:', data);
      if (data.success) {
        document.getElementById('editCourseModal').style.display = 'none';
        await fetchAndRenderCourses();
      } else {
        alert(data.message || '修改课程失败');
        await fetchAndRenderCourses();
      }
    } catch (e) {
      alert('网络错误，修改课程失败');
      await fetchAndRenderCourses();
    }
  };
  document.getElementById('cancelEditCourseBtn').onclick = function () {
    document.getElementById('editCourseModal').style.display = 'none';
  };
  document.getElementById('closeEditCourseModal').onclick = function () {
    document.getElementById('editCourseModal').style.display = 'none';
  };
  window.addEventListener('click', function (event) {
    var modal = document.getElementById('editCourseModal');
    if (event.target === modal) {
      modal.style.display = 'none';
    }
  });
}

// 动态填充教师下拉框
async function fillTeacherSelect() {
  const select = document.getElementById('teacherSelect');
  if (!select) return;
  select.innerHTML = '<option value="">加载中...</option>';
  try {
    const res = await fetch('/api/admin/users?status=approved', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
      }
    });
    const data = await res.json();
    if (data && data.users) {
      // 只保留教师
      const teachers = data.users.filter(u => u.role === 'teacher');
      if (teachers.length === 0) {
        select.innerHTML = '<option value="">无可用教师</option>';
      } else {
        select.innerHTML = teachers.map(t => {
          const realName = t.real_name || t.profile_real_name || t.username;
          return `<option value="${t.username}">${realName}</option>`;
        }).join('');
      }
    } else {
      select.innerHTML = '<option value="">无可用教师</option>';
    }
  } catch (e) {
    select.innerHTML = '<option value="">加载失败</option>';
  }
}

// 批量删除按钮事件
function bindBatchDeleteCourses() {
  var batchDeleteBtn = document.getElementById('batchDeleteBtn');
  if (batchDeleteBtn) {
    batchDeleteBtn.addEventListener('click', async function () {
      var checkedBoxes = document.querySelectorAll('.course-checkbox:checked');
      if (checkedBoxes.length === 0) {
        alert('请先选择要删除的课程');
        return;
      }
      if (!confirm('确定要删除选中的课程吗？')) return;
      var ids = Array.from(checkedBoxes).map(cb => cb.value);
      // 逐个删除（可优化为后端批量接口）
      for (let id of ids) {
        try {
          const res = await fetch(`/api/courses/${id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json' } });
          const data = await res.json();
          if (!data.success) {
            alert(`删除课程ID ${id} 失败：` + (data.message || '未知错误'));
          }
        } catch (e) {
          alert(`删除课程ID ${id} 网络错误`);
        }
      }
      await fetchAndRenderCourses();
    });
  }
}

// 绑定新增课程表单事件
function bindAddCourseForm() {
  var form = document.getElementById('addCourseForm');
  if (form) {
    form.onsubmit = handleAddCourse;
  }
}